using Microsoft.AspNetCore.Mvc;
using WebAPI.Application.Common.Interface;
using WebAPI.Application.ReqDto;
using WebAPI.Application.ResDto;
using WebAPI.Domain.Entity;
using WebAPI.Infrastructure.Utils;

namespace WebAPI.API.Controllers
{
    [ApiController]
    [Route("[Controller]")]
    public class UserController : ControllerBase
    {
        private readonly IRepository<AppUser> _user;
        private readonly IIdentityService _identityService;
        private readonly IRepository<AppUser> _appUserRespository;
        public UserController(IRepository<AppUser> user, IIdentityService identityService, IRepository<AppUser> appUserRespository)
        {
            _user = user;
            _identityService = identityService;
            _appUserRespository = appUserRespository;
        }

        // 返回所有表
        [HttpGet]
        public IEnumerable<AppUser> Index()
        {
            // throw new Exception("这有个异常");
            var users = _user.Table.ToArray();
            return users;
        }

        // 添加
        [HttpPost]
        public String CreateUser(AppUser entity)
        {
            var user = _user.AddAsync(entity);
            var res = new
            {
                code = 10001,
                msg = "添加成功",
                data = user.Result
            };

            return res.SerializeObject();
        }

        // 修改
        [HttpPut]
        [Route("{id}")]
        public String EditUser(Guid id, AppUser entity)
        {
            var userA = _user.GetById(id).Result;
            if (userA != null)
            {
                userA.Username = entity.Username;
                userA.Password = entity.Password;
                _user.UpdateAsync(entity);
            }
            var res = new
            {
                code = 10002,
                msg = "修改成功",
                data = userA,
            };
            return res.SerializeObject();
        }

        // 删除
        [HttpDelete]
        [Route("{id}")]
        public string DeleteUser(Guid id, AppUser entity)
        {
            var user = _user.DeleteAsync(id, false);

            var res = new
            {
                code = 10002,
                msg = "删除成功",
                data = user,
            };
            return res.SerializeObject();
        }

        [HttpPost("token")]
        public async Task<IActionResult> Authenticate([FromBody] UserForAuth userForAuth)
        {
            if (!_identityService.ValidateUserAsync(userForAuth))
            {
                return Unauthorized();
            }

            return Ok(new { Token = await _identityService.GenerateToken() });
        }

        [HttpPost]
        [Route("refreshtoken")]
        public async Task<IActionResult> RefreshToken(AppToken appToken)
        {
            var tokenToReturn = await _identityService.RefreshTokenAsync(appToken);
            return Ok(tokenToReturn);
        }


    }
}